<script setup>
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import * as echarts from "echarts";
import { useScaleStore } from "@/stores/scaleStore";

const props = defineProps({
  title: {
    type: String,
    default: "潮位数据",
  },
  tideData: {
    type: Array,
    default: () => [],
  },
  closeEvent: Function,
});

const closeClick = () => {
  props?.closeEvent();
};

let myChart = null;
let resizeObserver = null;
const chartDom = ref(null);
const boxWrapRef = ref(null);
const headerRef = ref(null);
const isDragging = ref(false);
const startPos = ref({ x: 0, y: 0 });
const currentPos = ref({ x: 0, y: 0 });
const currentScale = ref(1); // 当前窗口缩放比例
const isResizing = ref(false);
const resizeDirection = ref(null);
const startSize = ref({ width: 600, height: 500 });
const currentSize = ref({ width: 600, height: 500 });

const scaleStore = useScaleStore();

// 监听scaleStore的变化
watch(
  () => scaleStore.currentScale,
  (newScale) => {
    currentScale.value = newScale || 1;
  },
  { immediate: true }
);

const handleMouseDown = (e) => {
  // 检查是否是缩放区域
  if (e.target.classList.contains("resize-handle")) {
    isResizing.value = true;
    resizeDirection.value = e.target.dataset.direction;
    startSize.value = { ...currentSize.value };
    startPos.value = { x: e.clientX, y: e.clientY };

    e.stopPropagation();
    e.preventDefault();
    document.addEventListener("mousemove", handleResizeMove);
    document.addEventListener("mouseup", handleResizeEnd);
    return;
  }

  // 原有拖动逻辑
  if (!headerRef.value || !headerRef.value.contains(e.target)) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  isDragging.value = true;
  startPos.value = {
    x: adjustedX - currentPos.value.x,
    y: adjustedY - currentPos.value.y,
  };

  e.stopPropagation();
  e.preventDefault();

  document.addEventListener("mousemove", handleMouseMove);
  document.addEventListener("mouseup", handleMouseUp);
};

const handleMouseMove = (e) => {
  if (!isDragging.value) return;

  const adjustedX = e.clientX / currentScale.value;
  const adjustedY = e.clientY / currentScale.value;

  const newX = adjustedX - startPos.value.x;
  const newY = adjustedY - startPos.value.y;

  currentPos.value = { x: newX, y: newY };

  if (boxWrapRef.value) {
    boxWrapRef.value.style.left = `${newX}px`;
    boxWrapRef.value.style.top = `${newY}px`;
  }

  e.preventDefault();
};

const handleMouseUp = () => {
  isDragging.value = false;
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
};

const handleResizeMove = (e) => {
  if (!isResizing.value) return;

  const deltaX = (e.clientX - startPos.value.x) / currentScale.value;
  const deltaY = (e.clientY - startPos.value.y) / currentScale.value;

  const newSize = { ...currentSize.value };

  switch (resizeDirection.value) {
    case "e":
      newSize.width = Math.max(400, startSize.value.width + deltaX);
      break;
    case "s":
      newSize.height = Math.max(300, startSize.value.height + deltaY);
      break;
    case "se":
      newSize.width = Math.max(400, startSize.value.width + deltaX);
      newSize.height = Math.max(300, startSize.value.height + deltaY);
      break;
  }

  currentSize.value = newSize;
  updateChartSize();
  e.preventDefault();
};

const handleResizeEnd = () => {
  isResizing.value = false;
  resizeDirection.value = null;
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
};

const updateChartSize = () => {
  if (myChart) {
    myChart.resize();
  }
};

const calculateInterval = () => {
  if (!chartDom.value) return 0;
  const width = chartDom.value.clientWidth;
  if (width < 500) {
    return Math.ceil(sortedTimes.length / 5);
  }
  return Math.ceil(sortedTimes.length / 10);
};

let sortedTimes = [];

onMounted(async () => {
  await new Promise((resolve) => requestAnimationFrame(resolve));

  if (!chartDom.value) {
    console.error("Failed to find the echarts container.");
    return;
  }

  myChart = echarts.init(chartDom.value);

  if (boxWrapRef.value) {
    const rect = boxWrapRef.value.getBoundingClientRect();
    currentPos.value = { x: rect.left, y: rect.top };
  }

  // 处理数据
  const timeGroups = {};
  props.tideData.forEach((item) => {
    const date = new Date(item.createTime);
    const timeKey = `${
      date.getMonth() + 1
    }/${date.getDate()} ${date.getHours()}:00`;

    if (!timeGroups[timeKey]) {
      timeGroups[timeKey] = {
        time: timeKey,
        observed: null,
        predicted: null,
      };
    }

    if (item.type === 0) {
      timeGroups[timeKey].observed = item.high;
    } else {
      timeGroups[timeKey].predicted = item.high;
    }
  });

  sortedTimes = Object.keys(timeGroups).sort((a, b) => {
    return (
      new Date(a.replace(/(\d+)\/(\d+) (\d+):00/, "2025/$1/$2 $3:00")) -
      new Date(b.replace(/(\d+)\/(\d+) (\d+):00/, "2025/$1/$2 $3:00"))
    );
  });

  const observedData = sortedTimes.map(
    (time) => timeGroups[time].observed || "-"
  );
  const predictedData = sortedTimes.map(
    (time) => timeGroups[time].predicted || "-"
  );

  const option = {
    title: {
      text: props.title,
      left: "center",
      textStyle: {
        color: "#38e1ff",
        fontSize: 18,
      },
    },
    tooltip: {
      trigger: "axis",
      formatter: (params) => {
        let result = `时间: ${sortedTimes[params[0].dataIndex]}<br/>`;
        params.forEach((param) => {
          const color = param.seriesName === "观测数据" ? "#38e1ff" : "#ff8c00";
          if (param.data !== "-") {
            result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color}"></span>`;
            result += `${param.seriesName}: ${param.data}m<br/>`;
          }
        });
        return result;
      },
    },
    grid: {
      left: "12%",
      right: "10%",
      bottom: "15%",
      top: "30px",
    },
    xAxis: {
      type: "category",
      data: sortedTimes,
      axisLabel: {
        color: "#FFFFFF",
        rotate: 30,
        interval: calculateInterval(),
        formatter: function (value) {
          const parts = value.split(" ");
          return parts[0] + "\n" + parts[1];
        },
        fontSize: 12,
        lineHeight: 16,
        margin: 15,
      },
      axisTick: {
        alignWithLabel: true,
      },
      boundaryGap: false,
    },
    yAxis: {
      type: "value",
      name: "潮高 (m)",
      nameTextStyle: {
        color: "#FFFFFF",
        padding: [0, 0, 0, 30],
      },
      axisLabel: {
        color: "#FFFFFF",
        fontSize: 14,
      },
      splitLine: {
        lineStyle: {
          color: "rgba(255, 255, 255, 0.1)",
        },
      },
    },
    series: [
      {
        name: "观测数据",
        data: observedData,
        type: "line",
        smooth: true,
        lineStyle: {
          color: "#38e1ff",
          width: 3,
        },
        itemStyle: {
          color: "#38e1ff",
        },
        symbol: "circle",
        symbolSize: 8,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(56, 225, 255, 0.5)" },
            { offset: 1, color: "rgba(56, 225, 255, 0.1)" },
          ]),
        },
      },
      {
        name: "预测数据",
        data: predictedData,
        type: "line",
        smooth: true,
        lineStyle: {
          color: "#ff8c00",
          width: 3,
        },
        itemStyle: {
          color: "#ff8c00",
        },
        symbol: "circle",
        symbolSize: 8,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(255, 140, 0, 0.5)" },
            { offset: 1, color: "rgba(255, 140, 0, 0.1)" },
          ]),
        },
      },
    ],
    dataZoom: [
      {
        type: "inside",
        start: 0,
        end: 100,
        zoomLock: false,
      },
      {
        start: 0,
        end: 100,
        height: 15,
        bottom: 5,
        handleSize: "80%",
        handleStyle: {
          color: "#38e1ff",
        },
      },
    ],
    legend: {
      data: ["观测数据", "预测数据"],
      textStyle: {
        color: "#fff",
        fontSize: 14,
      },
      right: 10,
      top: 40,
      itemWidth: 14,
      itemHeight: 10,
      itemGap: 10,
    },
  };

  myChart.setOption(option);

  resizeObserver = new ResizeObserver(() => {
    myChart.resize();
    myChart.setOption({
      xAxis: {
        axisLabel: {
          interval: calculateInterval(),
        },
      },
    });
  });
  resizeObserver.observe(chartDom.value);
});

onBeforeUnmount(() => {
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
  if (myChart) {
    myChart.dispose();
  }
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
  document.removeEventListener("mousemove", handleResizeMove);
  document.removeEventListener("mouseup", handleResizeEnd);
});
</script>

<template>
  <div
    class="popup-container"
    :style="{
      left: `${currentPos.x}px`,
      top: `${currentPos.y}px`,
      width: `${currentSize.width}px`,
      height: `${currentSize.height}px`,
    }"
  >
    <div class="pine"></div>
    <div class="box-wrap" ref="boxWrapRef">
      <!-- 标题栏区域 -->
      <div class="header-area" ref="headerRef" @mousedown="handleMouseDown">
        <div class="title-text">{{ title }}</div>
        <div class="close" @click="closeClick">X</div>
      </div>
      <!-- 图表区域 -->
      <div ref="chartDom" class="chart-container"></div>

      <!-- 缩放控制手柄 -->
      <div
        class="resize-handle resize-e"
        data-direction="e"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-s"
        data-direction="s"
        @mousedown="handleMouseDown"
      ></div>
      <div
        class="resize-handle resize-se"
        data-direction="se"
        @mousedown="handleMouseDown"
      ></div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.popup-container {
  position: fixed;
  z-index: 9999;
  cursor: default;
  min-width: 400px;
  min-height: 300px;
}

.box-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 10px;
  border: 1px solid #38e1ff;
  background-color: rgba(30, 80, 120, 0.7);
  box-shadow: 0 0 10px 2px #29baf1;
  animation: slide 1s;
  overflow: hidden;
  user-select: none;
}

/* 标题栏样式 */
.header-area {
  position: relative;
  height: 40px;
  background: linear-gradient(
    to right,
    rgba(20, 60, 100, 0.9),
    rgba(30, 80, 120, 0.9)
  );
  border-bottom: 1px solid #38e1ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  cursor: grab;

  &:active {
    cursor: grabbing;
  }
}

.title-text {
  color: #38e1ff;
  font-size: 18px;
  font-weight: bold;
  text-shadow: 0 0 5px rgba(56, 225, 255, 0.7);
}

.close {
  color: #fff;
  text-shadow: 2px 2px 2px #022122;
  cursor: pointer;
  font-size: 20px;
  transition: all 0.2s;

  &:hover {
    color: #ff6b6b;
    transform: scale(1.1);
  }
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: calc(100% - 40px); /* 减去标题栏高度 */
  padding: 10px;
  box-sizing: border-box;
}

/* 缩放控制手柄样式 */
.resize-handle {
  position: absolute;
  background: transparent;
  z-index: 10;
}

.resize-e {
  cursor: e-resize;
  width: 10px;
  height: 100%;
  right: 0;
  top: 0;
}

.resize-s {
  cursor: s-resize;
  width: 100%;
  height: 10px;
  bottom: 0;
  left: 0;
}

.resize-se {
  cursor: se-resize;
  width: 15px;
  height: 15px;
  right: 0;
  bottom: 0;
  background: #38e1ff;
  opacity: 0;
  transition: opacity 0.2s;
}

.box-wrap:hover .resize-se {
  opacity: 0.8;
}

@keyframes slide {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
